package com.ext.bootsecurity25.config;

import com.ext.bootsecurity25.entity.Account;
import com.ext.bootsecurity25.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.ArrayList;
import java.util.Collection;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    // 创建自定义的userDetailService用于获取用户信息
    @Bean
    protected UserDetailsService userDetailsService() {
        return new DefaultUserDetailsService();
    }

    class DefaultUserDetailsService implements UserDetailsService {
        @Autowired
        AccountMapper accountMapper;
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            if (username == null || "".equals(username.trim())) {
                throw new UsernameNotFoundException("用户名不能为空！");

            }
            Account account = accountMapper.getUsername(username);
            if (account == null) {
                throw new UsernameNotFoundException("用户名不存在！");
            }
            Collection<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();
            roles.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            roles.add(new SimpleGrantedAuthority("ROLE_USER"));
            /*for (String roleName : account.getRoles()) {
                roles.add(new SimpleGrantedAuthority(roleName));
            }*/
            return new User(account.getUsername(), account.getPassword(), account.getEnabled(), true, true, true,
                    roles);
        }

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // TODO Auto-generated method stub
        //BCryptPasswordEncoder使用这个加密方式
        // 本人不使用加密方式
        auth.userDetailsService(userDetailsService()).passwordEncoder(NoOpPasswordEncoder.getInstance());

       /* auth.userDetailsService(userDetailsService()).passwordEncoder(new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return charSequence.toString();
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return s.equals(charSequence.toString());
            }
        });*/
    }



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/visitAdminPage").hasRole("ADMIN")
                .antMatchers("/visitUserPage").hasRole("USER")// 所需要的格式为ROLE_USER,必须以ROLE_开头
                .anyRequest().authenticated()      //进行用户认证
                .and()
                .formLogin().successForwardUrl("/visitIndexPage").permitAll() //登录成功后的页面
                .and().csrf().disable();
    }

}
